<template>
    <view class="index-scrool-page">
        <view class="header-cont">
            <view class="header-left">
                <view class="image">
                    <image style="width: 100rpx;height: 100rpx;border-radius: 50%;padding-left: 30 rpx;"
                           class="image"
                           :fade-show="true"
                           mode="aspectFill"
                           :src=account?.avatar></image>
                </view>
                <view class="accountName">{{ account?.name }}</view>
            </view>
			<uni-icons style="font-size: 30px;margin-right: 20px;margin-top: 10px;" type="personadd" size="30" @click="toAddFriend()"></uni-icons>
        </view>

        <view class="list-cont">
            <uni-list>
                <uni-list :border="true" v-for="i in talkList" :key="i.id">
                    <!-- 右侧带角标 -->
                    <uni-list-chat :avatar-circle="true" :title=i.roomName :avatar=i.avatar :note=i.message
                                   :badge-text=i.unread
                                   :time=handleDate.formatTimestampToDateTime(i.time,3) link @click="toChatInfo(i)">
                    </uni-list-chat>
                </uni-list>
            </uni-list>

            <uni-list>
                <uni-list :border="true">

                </uni-list>
            </uni-list>
        </view>


    </view>
</template>

<script setup lang="ts">
import {ref, type Ref} from 'vue'
import {Icon} from '@iconify/vue';
import {request} from '@/api/request'
import {onLoad, onShow} from '@dcloudio/uni-app';
import type {ChatDto} from '@/api/model/chat/ChatDto';
import {handleDate} from '@/util/handleDate'
import type {AccountDto} from "@/api/model/account/AccountDto";
import { WEB_SOCKET } from '@/api/request';

const token = ref('')
const talkList: Ref<ChatDto[]> = ref([])
const account: Ref<AccountDto | undefined> = ref();

  onShow(()=>{
    findTalk()
  })

onLoad(() => {
  updateAccountData();
    findTalk()
    uni.$on('accountUpdated', updateAccountData);
    uni.connectSocket({
        url: `${WEB_SOCKET}/index-${account.value?.id}`,
        header: {
            'content-type': 'application/json'
        },
        method: 'GET',
        success() {
            console.log('WebSocket连接成功');
        },
        fail(err) {
            console.error('WebSocket连接失败', err);
        }
    });
})

uni.onSocketOpen(function () {
    console.log('WebSocket连接已打开');
});

uni.onSocketMessage(function (res) {
  findTalk()
});

uni.onSocketError(function (err) {
    console.error('WebSocket错误：', err);
});

uni.onSocketClose(function () {
    console.log('WebSocket连接已关闭');
});

function updateAccountData() {
    account.value = uni.getStorageSync('account');
}

const findTalk = async () => {
    const value = uni.getStorageSync('token');
    console.log('token' + token.value)
    const operation = {
        method: 'GET',
        url: `/main/chat-room/find`,
        data: '',
        tokenRequired: true // 新增，表示是否需要token
    }
    const res = await request(operation)
    talkList.value = res.data.chatRoomDto
}

const toChatInfo = (chatDto: ChatDto) => {
    let friendId: string = ''
    if (chatDto.userId == account.value?.id) {
        friendId = chatDto.friendId
    } else {
        friendId = chatDto.userId
    }
    uni.navigateTo({
        url: `/pages/chat/chatInfo?roomId=${chatDto.id}&friendId=${friendId}`
    })
}

const toAddFriend = ()=>{
  uni.navigateTo({
        url: `/pages/friend/find/find`
    })
}


</script>
<style lang="scss">
page {
  width: 100%;
  height: 100%;
}

@font-face {
  font-family: add;
  src: url('src/assets/images/addFriend.png');
}

.index-scrool-page {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}

.header-cont {
  width: 100%;
  height: 11%;
  display: flex;
  text-align: center;
  align-items: center;
  justify-content: space-between;
  background: #F1F5FF;

  .header-left {
	margin-top: 25px;
    margin-left: 20px;
    gap: 20px;
    display: flex;
    align-items: center;

    .accountName {
      margin: 0 20 rpx;
      font-size: 30 rpx !important;
      font-family: "宋体";
    }

    .image {
      width: 100 rpx;
      height: 100 rpx;
      border-radius: 50%;
    }
  }
}

.list-cont {
  height: 90%;
  overflow: scroll;
}


</style>
